<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  ~   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  --%>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
    <title>读写数据</title>
    <style>
        .nav-tabs [class*="icon-"] {
            margin-right: 10px;
            font-size: 14px;
        }
        .nav>li>a {
            position: relative;
            display: block;
            padding: 0px 0px 5px 0px;
        }
        /*
        .table-striped > tbody > tr:nth-of-type(odd) {
            background-color: #f8f8f8;
        }
        */
        .table-hover > tbody > tr:hover {
            background-color: #f5f5f5;
        }

        .bg-white{
            background-color: white;
        }
        .popover-content {
            padding: 9px 14px;
        }

    </style>
    <script>

        $(function () {

            initTable();

            $('input[id*="valueType-"]').click(function(){
                if ($(this).prop('checked')){
                    showValueView($(this).val());
                }
            });

            $.post("${ctx}/redis-api/getClusters", {}, function(data) {
                if (data.success){
                    var clusters = data.result;
                    var clusterList = $('#cluster-list');
                    for (var i = 0; i < clusters.length; i++){
                    //for (var i in clusters){//数组这样遍历，ie 8下面有问题，多了个reduce function
                        //$('#cluster-list').append('<li><a href="javascript:selectCluster('+clusters[i].id+',\''+clusters[i].clusterName+'\')"><i class="icon-code-fork"></i>'+clusters[i].clusterName+'</a></li>');
                        clusterList.append('<option value="'+clusters[i].id+'">'+clusters[i].clusterName+'</option>');
                    }

//                    clusterList.selectpicker({
//                        //liveSearch: true,
//                        //maxOptions: 1,
//                        //title:"请选择集群",
//                        width:'auto'
//                    });
                    clusterList.selectpicker('refresh');
                }
            });

            $("#search").click(function () {
                var clusterId = $('#cluster-list').val();
                if (clusterId == ""){
                    toastr.warning("请先从下拉框中选择一个集群！");
                    return;
                }
                if (!$("#search-form").valid()){
                    return;
                }
                var params = {key:$('#search-key').val(),clusterId:clusterId};
                $.post("${ctx}/redis-api/getkeysByKeyQuery", params, function (data) {
                    if (data.success){
                        var result = data.result;
                        /*
                         var keyList = [];
                         for (var i in result){
                         keyList.push({key: result[i]});
                         }
                         */
                        createKeyTable(result);
                    }
                });
            })

            $('#set-value').click(function () {
                var clusterId = $('#cluster-list').val();
                if (clusterId == ""){
                    toastr.warning("请先从下拉框中选择一个集群！");
                    return;
                }
                showValue();
            });

            $('#save-value').click(function () {
                var key = $('input[id="key"]').val();
                if (key == ''){
                    toastr.warning("请输入Redis Key的值！");
                    return;
                }
                var valueType = $('input[name="valueType"]:checked').val();
                var value = {dataType: valueType};
                var data;
                switch (valueType){
                    case 'string':
                        data = $('#value-string').val();
                        if (data == ''){
                            toastr.warning("请输入"+valueType+"类型的值！");
                            return;
                        }
                        break;
                    default:
                        data = $('#table-'+valueType).bootstrapTable('getData');
                        if (data.length == 0){
                            toastr.warning("请输入"+valueType+"类型的值！");
                            return;
                        }
                }
                value.data = data;
                var params = {key: key, value: encodeURIComponent($.toJSON(value)), clusterId:
                        $('#cluster-list').val()};
                $.post("${ctx}/redis-api/setValueByKey", params, function (data) {
                    if (data.success){
                        toastr.success("保存成功！");
                        $('#data-detail').modal('hide');
                        $("#search").click();
                    }
                });
            });

        });

        var keyTable = null;
        function createKeyTable(data){
            if (keyTable != null){
                keyTable.bootstrapTable('load', data);
                keyTable.bootstrapTable('selectPage', 1);
                return;
            }
            keyTable = $('#keys-table').bootstrapTable({
                uniqueId: "id",
                classes: "table table-striped table-no-bordered",
                striped: false,
                singleSelect: false,
                pagination: true,
                data: data,
                locale: "zh-US" ,
                columns: [{
                    title: 'Key查询列表（点击将进行升序或倒序排序）',
                    field: 'key',
                    halign: 'center',
                    align: 'left',
                    sortable: true,
                    valign: 'middle',
                    width: '45%',
                    cellStyle: function(value, row, index){
                        return {css:{'padding-left': '100px'}};
                    }
//                },{
//                    title: '内存占用（字节）',
//                    field: 'memory',
//                    halign: 'center',
//                    align: 'right',
//                    sortable: true,
//                    valign: 'middle',
//                    width: '20%',
//                    cellStyle: function(value, row, index){
//                        return {css:{'padding-right': '50px'}};
//                    }
                }, {
                    title: '',
                    field: 'id',
                    align: 'center',
                    width: '100px',
                    formatter:function(value, row, index){
                        var e = '<a href="#" onclick="showValue(\''+ row.key + '\')">查看值</a> ';
                        return e;
                    }
                }]
            });
        }

        function showValue(key){
            $('[id*="table-"]').bootstrapTable('removeAll');
            if (key != null){
                $('#key').val(key);
                var params = {key:key, clusterId:$('#cluster-list').val()};
                $.post('${ctx}/redis-api/getValueByKey', params, function (data) {
                    if (data.success){
                        var dataType = data.result.dataType;
                        showValueView(dataType);

                        var value = data.result.data;
                        if (dataType == 'string'){
                            $('#value-string').val(value);
                        }else{
                            $('#table-'+dataType).bootstrapTable('load', value);
                        }

                        $('#data-detail').modal('show');
                    }
                });
            }else{
                showValueView('string');
                $('#data-form')[0].reset();
                $('#data-detail').modal('show');
            }
        }

        function showValueView(valueType) {
            $('[id*="view-"]').hide();
            $('[id*="view-' + valueType + '"]').show();
            $('input[id="valueType-'+valueType+'"]').prop('checked', 'checked');
        }

        function initTable(){
            $.fn.bootstrapTable.locales['zh-CN'] = {
                formatShowingRows: function(pageFrom, pageTo, totalRows) {
                    return '显示 ' + pageFrom + ' / ' + pageTo + '，共 ' + totalRows + ' 条 ';
                },
                formatRecordsPerPage: function (pageNumber) {
                    return '每页显示 ' + pageNumber + '条';
                },
                formatNoMatches: function () {
                    return '当前没有数据';
                }
            };

            var options = {
                uniqueId: "id",
                classes: "table table-hover table-no-bordered bg-white",
                striped: false,
                singleSelect: false,
                showHeader: true,
                pagination: true,
                pageSize: 5,
                pageList: [5,20],
                //checkbox: true,
                //height: 235,
                sortable: false,
                locale: "zh-US"
            };

            $('#table-list,#table-set').bootstrapTable($.extend(options, {
                columns: [{
                    field: 'state',
                    checkbox: true
                },{
                    title: '',
                    field: 'value',
                    halign: 'left',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入值'},
                    cellStyle: function(value, row, index){
                        return {css:{'word-wrap':'break-word','word-break':'break-all'}};
                    }
                }],
            }));

            $('#table-zset').bootstrapTable($.extend(options, {
                onEditableSave: function (field, row, oldValue, $element) {
                    if (field == 'score'){
                        var newValue = parseFloat(row[field]);
                        //if (isNaN(newValue)){
                        if (row[field] == '' || isNaN(row[field])){
                            toastr.warning("输入的权重值不合法！");
                            newValue = oldValue;
                        }
                        newValue += "";
                        $element.data('value', newValue);
                        row[field] = newValue;
                        setTimeout(function () {
                            $element.text(newValue);
                        },200);
                    }
                },
                columns: [{
                    field: 'state',
                    checkbox: true
                },{
                    title: '值',
                    width: '90%',
                    field: 'value',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入值'},
                    cellStyle: function(value, row, index){
                        return {css:{'word-wrap':'break-word','word-break':'break-all'}};
                    }
                },{
                    title: '权重',
                    width: '10%',
                    field: 'score',
                    halign: 'right',
                    align: 'right',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入权重值'},
                    cellStyle: function(value, row, index){
                        return {css:{'word-wrap':'break-word','word-break':'break-all'}};
                    }
                }],
            }));

            $('#table-hash').bootstrapTable($.extend(options, {
                columns: [{
                    field: 'state',
                    checkbox: true
                },{
                    title: '字段名',
                    width: '50%',
                    field: 'field',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入字段名'},
                    cellStyle: function(value, row, index){
                        return {css:{'word-wrap':'break-word','word-break':'break-all'}};
                    }
                },{
                    title: '字段值',
                    width: '50%',
                    field: 'value',
                    halign: 'center',
                    align: 'left',
                    valign: 'middle',
                    editable: {type: 'text',title: '请输入字段值'},
                    cellStyle: function(value, row, index){
                        return {css:{'word-wrap':'break-word','word-break':'break-all'}};
                    }
                }],
            }));

            var initActionClick = function (valueType) {
                var tableList = $('#table-'+valueType);
                $("#appendBtn-"+valueType).click(function() {
                    if (valueType == 'zset'){
                        tableList.bootstrapTable('append',{value:'', score:0}).bootstrapTable('lastPage');
                    }else if (valueType == 'hash'){
                        tableList.bootstrapTable('append',{field:'', value:''}).bootstrapTable('lastPage');
                    }else{
                        tableList.bootstrapTable('append',{value:''}).bootstrapTable('lastPage');
                    }
                });
                $('#removeBtn-'+valueType).click(function() {
                    var selections = tableList.bootstrapTable('getSelections');
                    if (selections.length == 0){
                        if (tableList.bootstrapTable('getData').length == 0){
                            toastr.warning("当前没有数据可供删除！");
                        }else{
                            toastr.warning("请在需要删除的数据前面打钩！");
                        }
                        return;
                    }
                    var values = $.map(selections, function (row) {
                        return row.value;
                    });
                    tableList.bootstrapTable('remove', {
                        field: 'value',
                        values: values
                    });
                });
            }
            initActionClick('list');
            initActionClick('set');
            initActionClick('zset');
            initActionClick('hash');

        }

    </script>
</head>

<body>

<div class="page-title">
    <div class="btn-group pull-right">
        <%--<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">选择集群<span class="caret"></span></button>--%>
        <%--<ul class="dropdown-menu dropdown-menu-right" id="cluster-list">--%>
        <%--</ul>--%>
        <select id="cluster-list" class="selectpicker show-tick" title="请选择集群" data-live-search="true" data-size="5">
        </select>
    </div>
    <h3>读写数据</h3>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="widget-container fluid-height clearfix">
            <div class="heading">
                <i class="icon-table"></i>根据关键字查询Key
            </div>
            <div class="widget-content padded clearfix">
                <form class="form-horizontal clearfix" id="search-form">
                    <div class="col-md-4">
                        <div class="col-lg-12 col-sm-12 input-group">
                            <input placeholder="请输入Redis Key关键字" id="search-key" name="search-key" class="form-control" required="true" minlength="2">
                            <span class="input-group-btn" style="vertical-align: top">
                                <button class="btn btn-primary" id="search" type="button">查询</button>
                            </span>
                        </div>
                    </div>
                    <button type="button" class="btn btn-primary pull-right" id="set-value">设置键值</button>
                </form>

                <table id="keys-table">
                </table>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="data-detail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" style="width: 900px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">设置键值</h4>
            </div>
            <form class="form-horizontal" id="data-form">
                <div class="modal-body" style="margin-right: 20px">
                    <div class="form-group">
                        <label for="key" class="col-md-1 control-label">键</label>
                        <div class="col-md-11">
                            <input type="text" class="form-control required" id="key" name="key" placeholder="请输入Redis Key">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-1 control-label">值</label>
                        <div class="col-md-11">
                            <label class="radio-inline">
                                <input id="valueType-string" name="valueType" type="radio" value="string" checked>
                                <span>string</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-list" name="valueType" type="radio" value="list">
                                <span>list</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-set" name="valueType" type="radio" value="set">
                                <span>set</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-zset" name="valueType" type="radio" value="zset">
                                <span>zset</span>
                            </label>
                            <label class="radio-inline">
                                <input id="valueType-hash" name="valueType" type="radio" value="hash">
                                <span>hash</span>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="value-string" class="col-md-1 control-label"></label>
                        <div class="col-md-11" id="view-string">
                        <textarea class="form-control" id="value-string" name="value" placeholder="" rows="10"></textarea>
                        </div>
                        <div class="col-md-11" id="view-list">
                            <div class="col-md-11">
                                <table id="table-list"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-list" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-list" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-set">
                            <div class="col-md-11">
                                <table id="table-set"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-set" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-set" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-zset">
                            <div class="col-md-11">
                                <table id="table-zset"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-zset" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-zset" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                        <div class="col-md-11" id="view-hash">
                            <div class="col-md-11">
                                <table id="table-hash"></table>
                            </div>
                            <div class="col-md-1">
                                <button type="button" id="appendBtn-hash" class="btn btn-default" >添加</button>
                                <button type="button" id="removeBtn-hash" class="btn btn-default" >删除</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="save-value">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>
